<?php

namespace App\Services\Impl;

use App\Constants\SystemEventTypeEnum;
use App\Constants\VivoEventTypeEnum;
use App\Entity\Bo\ReportEventBo;
use App\Model\Business\AppAdAccount;
use App\Model\Report\VivoDevice;
use Carbon\Carbon;

class VivoService
{
    public array $systemEventTypeToVivoEventTypeMap = [];

    public function __construct()
    {
        $this->systemEventTypeToVivoEventTypeMap = [
            SystemEventTypeEnum::ACTIVATION->value => VivoEventTypeEnum::ACTIVATION->value,
            SystemEventTypeEnum::NEXT_DAY->value   => VivoEventTypeEnum::NEXT_DAY->value,
            SystemEventTypeEnum::KEY->value        => VivoEventTypeEnum::REGISTER->value,
        ];
    }

    public function reportLaunch($appId, $oaid)
    {
        $device = VivoDevice::findReportAscribeDevice($appId, $oaid);

        if ($device) {
            if ($device->launch_status != 1) {
                $device->launch_status = 1;
                $device->launch_time   = Carbon::now()->toDateTimeString();
                $device->save();
            }
        }
    }

    public function reportEvent(ReportEventBo $reportEventBo)
    {
        $app             = $reportEventBo->getApp();
        $appId           = $reportEventBo->getAppId();
        $systemEventType = $reportEventBo->getEventType();
        $oaid            = $reportEventBo->getOaid();

        $eventType = $this->systemEventTypeToVivoEventTypeMap[$systemEventType];
        throw_error_if(!$eventType, "vivoEventType 不正确");

        // 32位的oaid不用回传，只回传64位的，32位的媒体侧识别不了
        throw_error_if(strlen($oaid) != 64, "无效oaid");

        $device = $this->getReportDevice($reportEventBo);
        throw_error_if(!$device->request_id, "没有广告计划，不上报");
    }

    private function getVivoReportConfig($appId, $advertiserId)
    {
        $adAccount = AppAdAccount::query()
            ->where("app_id", $appId)
            ->where("channel_type_unique_id", $advertiserId)
            ->first();

    }

    public function getReportDevice(ReportEventBo $reportEventBo)
    {
        $appId     = $reportEventBo->getAppId();
        $bigDevice = $reportEventBo->getBigDevice();
        $oaid      = $reportEventBo->getOaid();

        $device = VivoDevice::findReportAscribeDevice($appId, $oaid);
        throw_error_if(!$device, "没有设备信息");

        if ($bigDevice) {
            $bigDevice->sub_device_id = $device->id;
            $bigDevice->save();
        }

        return $device;
    }
}